 /****************
 *@description: im数据面板   @/myPocket/dataPanel/index
 *@author: Xhd
 *@API: 高贤亮、陈浩天
 *@date: 2023-12-27 09:39:57
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import { Modal } from "antd";
import moment from 'moment';
import TheQueryForm from '@/components/TheQueryForm';
import TheTable from "@/components/TheTable";
import ThePagination from '@/components/ThePagination';
import TheButton from '@/components/TheButton';
import ChartData from "./components/chartData";
import { apiGiftDataBoardCount, apiGetStatisticsPage, apiGetStatisticsExport } from "@/request/dataPanel";
import { exportSheetTable } from "@/utils/exportTable";
import _ from 'lodash';
import "./style/style.less";

class DataPanel extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef()
    this.state = {
      // today: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      today: moment().subtract(1, 'days').format('yyyy-MM-DD'),
      dataCount: [],
      dataSource: [],
      form_show: true,
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      searchOption: [
        { field: 'time', label: '统计时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
      ],
      queryForm: {
        startTime: "",
        endTime: ""
      },
      columns: [
        {
          title: '时间',
          dataIndex: 'timeStr',
          key: 'timeStr'
        },
        {
          title: '充值成功金额（元）',
          dataIndex: 'rechargeSuccessAmount',
          key: 'rechargeSuccessAmount', 
        },
        {
          title: '收益兑换宠币 金额（元）',
          dataIndex: 'giftIncomeExchangePetCoins',
          key: 'giftIncomeExchangePetCoins',
        },
        {
          title: 'apple支付（元）',
          dataIndex: 'applePayAmount',
          key: 'applePayAmount',
        },
        {
          title: '支付宝支付（元）',
          dataIndex: 'aliPayAmount',
          key: 'aliPayAmount',
        },
        {
          title: '支付宝提现成功金额（元）（不含手续费）',
          dataIndex: 'alipayWithdrawalSuccessAmountExcludingHandlingFee',
          key: 'alipayWithdrawalSuccessAmountExcludingHandlingFee',
        },
        {
          title: '支付宝提现成功金额（元）（包含手续费）',
          dataIndex: 'alipayWithdrawalSuccessAmountIncludingHandlingFee',
          key: 'alipayWithdrawalSuccessAmountIncludingHandlingFee',
        },
        {
          title: '银行卡提现成功金额（元）（不含手续费）',
          dataIndex: 'successfulBankCardWithdrawalAmountExcludingHandlingFee',
          key: 'successfulBankCardWithdrawalAmountExcludingHandlingFee',
        },
        {
          title: '银行卡提现成功金额（元）（包含手续费）',
          dataIndex: 'successfulBankCardWithdrawalAmountIncludingHandlingFee',
          key: 'successfulBankCardWithdrawalAmountIncludingHandlingFee',
        },
        // {
        //   title: '宠币账户收入（个）',
        //   dataIndex: 'coinAccountIncome',
        //   key: 'coinAccountIncome',
        //   render: (text) => {
        //     return (Number(text) /10).toString()
        //   }
        // },
        // {
        //   title: '宠币账户赠礼支出 （个）',
        //   dataIndex: 'coinAccountGiftExpend',
        //   key: 'coinAccountGiftExpend',
        //   render: (text) => {
        //     return (Number(text) /10).toString()
        //   }
        // },
        // {
        //   title: '礼物收益收入（元）',
        //   dataIndex: 'giftIncome',
        //   key: 'giftIncome',
        // },
        // {
        //   title: '提现成功金额（元）',
        //   dataIndex: 'withdrawSuccessAmount',
        //   key: 'withdrawSuccessAmount',
        // },
      ],
      total: 0,
      range: 1
    }
  }
  componentDidMount() {
    // this.getData()
    this.getStatisticsPage()
  }

  getData = async () => {
    await apiGiftDataBoardCount({ type: 1 }).then(res => {
      if (res.code === 0) {
        let data = res.data
        this.setState({
          dataCount: [
            {
              name: "宠币账户收入累计（个）",
              key: "petCoinsReceive",
              data: (Number(data.petCoinsReceive) /10).toString()
            },
            {
              name: "宠币账户支出累计（个）",
              key: "petCoinsSend",
              data: (Number(data.petCoinsSend) /10).toString()
            },
            {
              name: "宠币账户余额总计（个）",
              key: "petCoinsBalance",
              data: (Number(data.petCoinsBalance) /10).toString()
            },
            {
              name: "礼物收益金额累计(元)",
              key: "giftIncome",
              data: (Number(data.giftIncome) /100).toString()
            },
            {
              name: "提现中金额(元)",
              key: "withdrawalIng",
              data: (Number(data.withdrawalIng) /100).toString()
            },
            {
              name: "提现成功金额(元)",
              key: "withdrawalSuccess",
              data: (Number(data.withdrawalSuccess) /100).toString()
            },
            {
              name: "收益账户余额总计(元)",
              key: "giftIncomeBalance",
              data: (Number(data.giftIncomeBalance) /100).toString()
            },
            {
              name: "手续费累计(元)",
              key: "commission",
              data: (Number(data.commission) /100).toString()
            },
          ]
        })
      }
    }).catch(() => {

    })
  }

  getStatisticsPage = async () => {
    const { pageData, queryForm } = this.state
    await apiGetStatisticsPage({ ...pageData, ...queryForm, }).then(res => {
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          total: res.totalCount,
          range: res.totalPage
        })
      }
    })
  }

  onFormSearch(value) {
    if (value && value.hasOwnProperty('time')) {
      value.startTime = moment(value.time[0]).format('yyyy-MM-DD')
      value.endTime = moment(value.time[1]).format('yyyy-MM-DD')
      delete value.time
    }
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...value }
    }, () => {
      this.getStatisticsPage()
    })
  }

  onReset() {
    this.setState({
      queryForm: {
        startTime: "",
        endTime: ""
      }
    }, () => {
      this.pageChange(1, 10)
    })
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getStatisticsPage()
    })
  };

  toExport = async () => {
    const { queryForm } = this.state;
    if (_.isEmpty(queryForm.startTime)) {
      Modal.warning({ title: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。', });
      return
    }
    this.setState({ exportLoading: true })
    let params = {
      ...queryForm,
    }
    let res = await apiGetStatisticsExport({ ...params })
    if (res.code === 0) {
      let th_arr = [
        {
          title: 'IM统计',
          prop: '',
          children: [
            {
              title: "时间",
              prop: "timeStr",
            },
            {
              title: "充值成功金额（元）",
              prop: "rechargeSuccessAmount",
            },
            {
              title: "收益兑换宠币 金额（元）",
              prop: "giftIncomeExchangePetCoins",
            },
            {
              title: "apple支付（元）",
              prop: "applePayAmount",
            },
            {
              title: "支付宝支付（元）",
              prop: "aliPayAmount",
            },
            {
              title: "支付宝提现成功金额（元）（不含手续费）",
              prop: "alipayWithdrawalSuccessAmountExcludingHandlingFee",
            },
            {
              title: "支付宝提现成功金额（元）（包含手续费）",
              prop: "alipayWithdrawalSuccessAmountIncludingHandlingFee",
            },
            {
              title: "银行卡提现成功金额（元）（不含手续费）",
              prop: "successfulBankCardWithdrawalAmountExcludingHandlingFee",
            },
            {
              title: "银行卡提现成功金额（元）（包含手续费）",
              prop: "successfulBankCardWithdrawalAmountIncludingHandlingFee",
            },
            // {
            //   title: "宠币账户收入（个）",
            //   prop: "coinAccountIncome",
            // },
            // {
            //   title: "宠币账户赠礼支出 （个）",
            //   prop: "coinAccountGiftExpend",
            // },
            // {
            //   title: "礼物收益收入（元）",
            //   prop: "giftIncome",
            // },
            // {
            //   title: "提现成功金额（元）",
            //   prop: "withdrawSuccessAmount",
            // },
          ]
        },
      ]
      // res.data.map((item) => {
      //   item.coinAccountIncome = (Number(item.coinAccountIncome) /10).toString()
      //   item.coinAccountGiftExpend = (Number(item.coinAccountGiftExpend) /10).toString()
      //   return item
      // })
      let tb_arr = res.data
      exportSheetTable({ fileName: 'IM统计', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
    }
    this.setState({ exportLoading: false })
  }


  render() {
    const {   //today, dataCount,
      columns, dataSource, pageData: { pageNo, pageSize }, range, total, form_show, searchOption } = this.state
    return (<div className='p-layout-box'>
      {/* <div >
        统计时间：{today}
        <div style={{ display: "flex", borderRadius: "10px", overflow: "hidden" }}>
          {dataCount.map((v, i) => {
            return <div className='cardData' style={{ width: "12.5%", backgroundColor: "#ddd", borderRight: "1px solid #aaa", lineHeight: "40px", textAlign: "center" }}>
              <p>{v.name}</p>
              <p style={{ fontWeight: "600" }}>{v.data}</p>
            </div>
          })}
        </div>
      </div> */}
      <div>
        <ChartData></ChartData>
      </div>
      <div>
        <div style={{ marginTop: 30, fontWeight: 700, fontSize: 22 }}>统计</div>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheButton style={{marginBottom:"5px"}} haspermi={['myPocket:dataPanel:export']} size="middle" onClick={() => this.toExport()} type="primary">导出</TheButton>
        <TheTable scroll={{ x: 'max-content' }} columns={columns} dataSource={dataSource} />
        <p>（当天的实时获取）</p>
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
          showTotal = {()=>`共${range}页/${total}条数据`}
        />
      </div>
    </div>)
  }
}

export default DataPanel